package com.lx.zxs.controller;
 
import com.alibaba.fastjson.JSONObject;
import com.lx.zxs.entity.Contacts;
import com.lx.zxs.entity.User;
import com.lx.zxs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
 
    @Autowired
    private UserService userService;



    @GetMapping(value = "/updateUser")
    public void updateUser(@RequestParam(value = "user",required = false) String user){
        User user1 = JSONObject.parseObject(user,User.class);
        userService.updateUser(user1);
    }

    @GetMapping(value = "/registerUser")
    public void doRegister(@RequestParam(value = "user",required = false) String user) {
        User user1 = JSONObject.parseObject(user,User.class);
        if(userService.findUserByUserName(user1.getUsername())!=null){
            return ;
        }else{
            userService.addUser(user1);
        }

    }
    @GetMapping("getUser/{id}")
    public User GetUser(@PathVariable int id){
        return userService.Sel(id);
    }


    @GetMapping("updateTime")
    public void updateTime(@RequestParam(value = "id",required = false) Integer id){
        userService.updateTime(id);
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public User getUserById(@RequestParam(value = "username") String username,
                            @RequestParam(value = "pass") String pass, HttpServletRequest req){


        User user = userService.getUserByNameAndPass(username, pass);
        return user;
    }


    @GetMapping("getLinkMan/{id}")
    public List<Map> getLinkMan(@PathVariable int id){
        return userService.getLinkMan(id);
    }

    @GetMapping(value = "/findUserByUsername")
    public Map findUserByUserName(@RequestParam(value = "username",required = false) String username){
        return userService.findUserByUserName(username);
    }

    @GetMapping(value = "/getChatData")
    public List<Map> getCharData(@RequestParam(value = "id1",required = false) String id1,
                                @RequestParam(value = "id2",required = false) String id2){
        return userService.getChatData(id1,id2);
    }

    @GetMapping(value = "/addChatData")
    public Map addChatData(@RequestParam(value = "direction",required = false) Integer direction,
                                 @RequestParam(value = "type",required = false) Integer type,
                                 @RequestParam(value = "content",required = false) String content,
                                 @RequestParam(value = "uid",required = false) Integer uid,
                                 @RequestParam(value = "lid",required = false) Integer lid,
                                 @RequestParam(value = "linkName",required = false) String linkName){

        return userService.addChatData(uid,lid,direction,type,content,null,linkName);
    }

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file, ModelMap model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        int id = Integer.parseInt(request.getParameter("id"));
        String fileName = updateFile(request, file,id);
        return fileName;
    }

    @RequestMapping("/getUserLogo")
    public void getUserLogo(HttpServletRequest request,
                            HttpServletResponse response, String path) {
        response.setContentType("image/jpeg"); // 设置返回内容格式
        File file = new File(path); // 括号里参数为文件图片路径
        if (file.exists()) { // 如果文件存在
            InputStream in;
            try {
                in = new FileInputStream(file);
                OutputStream os = response.getOutputStream(); // 创建输出流
                byte[] b = new byte[1024];
                while (in.read(b) != -1) {
                    os.write(b);
                }
                in.close();
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private String updateFile(HttpServletRequest request,MultipartFile files,Integer id) {
        MultipartFile file = files;
        if (!file.isEmpty()){
            try {
                // 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
                // )
                String filePath = request.getSession().getServletContext()
                        .getRealPath("/")
                        + "upload/"+id +'/'+ file.getOriginalFilename();

                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists()){
                    saveDir.getParentFile().mkdirs();
                }
                // 转存文件 保存到服务器地址上，路径在filePath
                file.transferTo(saveDir);
                /**请求图片服务器 返回字符串
                 * */
                //得到图片全名
                String absolutePath = saveDir.getAbsolutePath();
                userService.updateUserAvatar(id,absolutePath);
                String canonicalPath = saveDir.getCanonicalPath();
                System.out.println(absolutePath+"---"+canonicalPath);
                //absolutePath是文件的绝对路径，下面jsp中，预览头像时，需要回传到getUserLogo 接口中
                return absolutePath;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}